<template>
  <el-card :body-style="bodyStyle">
    <div class="ver-layout">
      <div class="header-layout">
        <el-upload class="upload" :limit="1" :show-file-list="false"
                   action="" :multiple="false" :on-change="importExcel"
                   accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
          <el-button size="mini" type="primary">上传名单Excel</el-button>
        </el-upload>
        <el-button size="small" type="text" class="excel-template" @click="downloadExcelTemplate">
          Excel模板下载
        </el-button>
      </div>
      <div class="info-layout">
        <el-tag size="small">男生{{ maleNum }}名</el-tag>
        <el-tag type="danger" size="small" class="second-tag">女生{{ femaleNum }}名</el-tag>
        <el-tag type="info" size="small" class="second-tag">共{{ this.tableData.length }}名</el-tag>
      </div>
    </div>
    <el-table :data="tableData" stripe border size="small" height="90%" style="margin-top: 10px;">
      <el-table-column type="index" label="#" :width="getIndexWidth" show-overflow-tooltip align="center"/>
      <el-table-column prop="username" label="姓名" :width="getTableWidth" show-overflow-tooltip align="center"/>
      <el-table-column prop="user_sex" label="性别" :width="getTableWidth" show-overflow-tooltip align="center"/>
    </el-table>
  </el-card>
</template>

<script>
import XLSX from 'xlsx'

export default {
  data() {
    return {
      keyMap: {
        "姓名": "username",
        "性别": "user_sex",
      },
      bodyStyle: {
        height: '88%',
        marginTop: "-10px"
      },
      tableData: []
    }
  },
  computed: {
    maleNum() {
      return this.tableData.filter(user => user.user_sex === '男').length
    },
    femaleNum() {
      return this.tableData.filter(user => user.user_sex === '女').length
    },
    getIndexWidth() {
      return document.body.clientWidth > 500 ? "" : 30
    },
    getTableWidth() {
      return document.body.clientWidth > 500 ? "" : 45
    }
  },
  methods: {
    downloadExcelTemplate() {
      let link = document.createElement("a");
      link.href = "https://mp-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b.cdn.bspapp.com/cloudstorage/学生名单模版.xls";
      link.style.display = "none"; //a标签隐藏
      link.download = '学生名单模版.xls';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link)
    },
    convertTable(data) {
      let headerObject = {}, headerFieldList = []
      data.forEach(item => Object.keys(item).forEach(key => headerObject[key] = key));
      headerFieldList = Object.keys(headerObject)
      if (!headerFieldList.includes("姓名") || !headerFieldList.includes("性别")) {
        this.$message.warning("上传模版格式不符！")
        return
      }
      data.forEach(item => {
        for (const key in item) {
          let newKey = this.keyMap[key]
          if (newKey) {
            item[newKey] = item[key]
            delete item[key]
          }
        }
      })
      this.tableData = data
      this.$emit("tableData", data)
      // console.log("data:", data)
      // this.$store.commit("question/set_user_batch", data)
    },
    // 导入表格
    importExcel(param) {
      // console.log(param);
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.file2Xce(param).then(item => {
        setTimeout(() => {
          loading.close()
          if (item && item.length > 0) {
            //xlsxJson就是解析出来的json数据,数据格式如下
            //[{sheetName:sheet1, sheet:sheetData}]
            if (item[0] && item[0].sheet && item[0].sheet.length) {
              let tableData = item[0].sheet  //把数据塞到表格预览
              this.convertTable(tableData)
            }
          }
        }, 2000)
      }).catch(error => {
        console.error(error)
        setTimeout(() => {
          loading.close()
        }, 2000)
      });
    },
    /**
     *解析文件
     */
    file2Xce(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          /* console.log("解析")
          console.log(result) */
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
      });
    }
  }
}
</script>

<style scoped>
.index-class {
  font-weight: bolder;
}

.excel-upload-input {
  display: none;
  z-index: -9999;
}

.header-layout {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.info-layout {
  margin-top: 5px;
  margin-left: 20px;
}

.second-tag {
  margin-left: 10px;
}

.excel-template {
  color: #999999;
  margin-left: 10px;
  text-decoration: underline;
}

@media screen and (max-width: 500px) {
  .header-layout {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .info-layout {
    margin-left: 0px;
  }

  .second-tag {
    margin-left: 0px;
  }

  /deep/ .el-card__body {
    padding: 5px;
  }
}
</style>
